package cn.zclong.student.web.servlet.admin;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;
import cn.zclong.student.domain.Student;
import cn.zclong.student.service.StuException;
import cn.zclong.student.service.StuService;
import cn.zclong.user.service.UserException;

/**
 * 管理员对学生的管理
 */
public class AdminStuServlet extends BaseServlet {
	private StuService stuService = new StuService();
	
	/**
	 * 管理员对学生的查询
	 */
	public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 1,调用service方法，得到所有学生信息
		 * 2，保存到request域，转发到adminjaps/admin/user/list.jsp";
		 */
		request.setAttribute("stuList", stuService.findAll());  
		return "f:/adminjsps/admin/student/list.jsp";
	}
	
	/**
	 * 管理员修改学生
	 */
	public String edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 1，封装表单数据
		 * 2，调用service方法完成修改工作
		 * 3，调用findAll()
		 */
		
		Student student = CommonUtils.toBean(request.getParameterMap(), Student.class);
		try {
			stuService.edit(student);
			return findAll(request, response);
		} catch (StuException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("student", student);
			return "f:/adminjsps/admin/student/mod.jsp";
		}
		
	}
	
	
	/**
	 * 管理员修改学生之前的加载工作
	 */
	public String editPre(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sid = request.getParameter("sid");
		request.setAttribute("student", stuService.load(sid));
		return "f:/adminjsps/admin/student/mod.jsp";
	}
	
	/**
	 * 管理员添加学生
	 */
	public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 1，获取表单数据
		 * 2，给uid赋值
		 * 3，调用service方法
		 * 4，调用findAll()方法
		 */
		Student student = CommonUtils.toBean(request.getParameterMap(), Student.class);
		
		System.out.println(student.getStuid());
		student.setSid(CommonUtils.uuid());
		
		
		try {
			stuService.add(student);
			
			return findAll(request, response);
		} catch (StuException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("student", student);
			return "f:/adminjsps/admin/student/add.jsp";
		}
	}
	
	
	/*
	 * 管理员删除学生
	 */
	public String delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 1,获取参数：uid
		 * 2,调用service方法，传递uid参数
		 * 	>如果抛出异常，保存异常信息，转发到msg.jsp显示
		 * 3，调用findAll()
		 */
		String sid = request.getParameter("sid");
		stuService.delete(sid);
		return findAll(request, response);
	}  
}
